package com.scm.service.impl;

import java.io.IOException;
import java.util.List;

import com.google.gson.Gson;
import com.scm.common.core.domain.entity.SysUser;
import com.scm.common.enums.ProductSourceEnum;
import com.scm.common.enums.ProductSyncStatusEnum;
import com.scm.converter.ProductConverter;
import com.scm.dto.resp.product.ProductSyncStatus;
import com.scm.dto.resp.product.ScmProductDo;
import com.scm.dto.resp.product.SelectProductPageResp;
import com.scm.factory.ProductFactory;
import com.scm.persist.model.ScmProduct;
import com.scm.persist.model.ScmProductDetailOms;
import com.scm.persist.model.ScmProductDetailOmsExample;
import com.scm.persist.model.ScmProductExample;
import com.scm.persist.mybatis.ScmProductDetailOmsMapper;
import com.scm.persist.mybatis.ScmProductMapper;
import com.scm.service.IScmProductService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


/**
 * 商品信息Service业务层处理
 * 
 * @author reptilemanager
 * @date 2024-04-11
 */
@Slf4j
@Service
public class ScmProductServiceImpl implements IScmProductService
{
    @Autowired
    private ScmProductMapper scmProductMapper;

    @Autowired
    private ScmProductDetailOmsMapper scmProductDetailOmsMapper;


    @Autowired
    private ProductFactory productFactory;



    /**
     * 查询商品信息
     * 
     * @param id 商品信息主键
     * @return 商品信息
     */
    @Override
    public ScmProductDo selectScmProductById(Long tenantId, Long id)
    {
        ScmProduct product= scmProductMapper.selectByPrimaryKey(tenantId,id);
        if(product==null){
            return null;
        }

        return productFactory.createProductDo(product);
    }

    /**
     * 查询商品信息列表
     * 
     * @param scmProduct 商品信息
     * @return 商品信息
     */
    @Override
    public SelectProductPageResp selectScmProductList(Long tenantId,ScmProduct scmProduct, Integer start, Integer size)
    {
        ScmProductExample example = new ScmProductExample();
        ScmProductExample.Criteria criteria= example.createCriteria();
        criteria.andTenantIdEqualTo(tenantId);
        if(StringUtils.isNotEmpty(scmProduct.getProductCode())){
            criteria.andProductCodeEqualTo(scmProduct.getProductCode());
        }
        if(StringUtils.isNotEmpty(scmProduct.getProductName())){
            criteria.andProductNameLike(scmProduct.getProductName());
        }

        RowBounds rowBounds = new RowBounds(start,size);
        int count = scmProductMapper.countByExample(example);
        List<ScmProduct> list = Lists.newArrayList();
        if(count>0){
            list =  scmProductMapper.selectByExampleWithRowbounds(example,rowBounds);
        }

        return SelectProductPageResp.builder().total(Long.valueOf(count)).list(list).build();
    }

    /**
     * 新增商品信息
     * 
     * @param scmProduct 商品信息
     * @return 结果
     */
    @Override
    public int insertScmProduct(SysUser sysUser, ScmProductDo scmProduct)
    {
        ScmProduct record = ProductConverter.convertScmProductDoToScmProduct(sysUser.getTenantId(),scmProduct);
        record.setCreateUser(String.valueOf(sysUser.getUserId()));
        record.setCreateTime(System.currentTimeMillis());
        record.setSource(ProductSourceEnum.SCM.getCode());
        scmProductMapper.insertSelective(record);

        ScmProductDetailOms scmProductDetailOms = ProductConverter.convertScmProductDoToScmProductDetailOms(sysUser.getTenantId(),scmProduct);
        scmProductDetailOms.setScmProductId(record.getId());
        scmProductDetailOms.setCreateUser(String.valueOf(sysUser.getUserId()));
        scmProductDetailOms.setCreateTime(System.currentTimeMillis());
        scmProductDetailOmsMapper.insertSelective(scmProductDetailOms);

        return 1;
    }

    /**
     * 修改商品信息
     * 
     * @param scmProduct 商品信息
     * @return 结果
     */
    @Override
    public int updateScmProduct(SysUser sysUser, ScmProductDo scmProduct)
    {

        ScmProduct record = ProductConverter.convertScmProductDoToScmProduct(sysUser.getTenantId(),scmProduct);
        record.setUpdateTime(System.currentTimeMillis());
        record.setUpdateUser(String.valueOf(sysUser.getUserId()));

        ScmProductDetailOms scmProductDetailOms = ProductConverter.convertScmProductDoToScmProductDetailOms(sysUser.getTenantId(),scmProduct);
        scmProductDetailOms.setUpdateTime(System.currentTimeMillis());
        scmProductDetailOms.setUpdateUser(String.valueOf(sysUser.getUserId()));
        scmProductMapper.updateByPrimaryKeySelective(record);

        ScmProductDetailOmsExample example = new ScmProductDetailOmsExample();
        example.createCriteria().andScmProductIdEqualTo(record.getId()).andTenantIdEqualTo(sysUser.getTenantId());

        scmProductDetailOmsMapper.updateByExampleSelective(scmProductDetailOms,example);
        return 1;
    }

    /**
     * 批量删除商品信息
     * 
     * @param ids 需要删除的商品信息主键
     * @return 结果
     */
    @Override
    public int deleteScmProductByIds(String ids)
    {
        return 1;
    }

    /**
     * 删除商品信息信息
     * 
     * @param id 商品信息主键
     * @return 结果
     */
    @Override
    public int deleteScmProductById(Long id)
    {
        return scmProductMapper.deleteByPrimaryKey(id);
    }


    public ProductSyncStatus syncProduct(Long tenantId, String source, String code, String userId )
    {

        ProductSyncStatus productSyncStatus  = new ProductSyncStatus();
        productSyncStatus.setProductCode(code);

        try {

            ScmProductExample example = new ScmProductExample();
            ScmProductExample.Criteria criteria = example.createCriteria();

            criteria.andSourceEqualTo(source).andProductCodeEqualTo(code);
            if(tenantId!=null&&tenantId!=0){
                criteria.andTenantIdEqualTo(tenantId);
            }

            List<ScmProduct>  list = scmProductMapper.selectByExample(example);

            if(org.apache.commons.collections4.CollectionUtils.isNotEmpty((list))){
                productSyncStatus.setStatus(ProductSyncStatusEnum.SyncEd);
                productSyncStatus.setMsg("商品编号："+code+"已存在，无需同步");
                productSyncStatus.setProductId(list.get(0).getId());
            }else{
                if(ProductSourceEnum.OMS.getCode().equals(source)){

                    OmsProductResp productResp = getOmsProductByCode(code);

                    if(productResp==null|| productResp.getData()==null||CollectionUtils.isEmpty(productResp.getData().getList())){
                        productSyncStatus.setStatus(ProductSyncStatusEnum.NoFind);
                        productSyncStatus.setMsg("商品编号："+code+"未在OMS中查询相关数据");
                        return productSyncStatus;
                    }

                    OmsProductResp.DataBean.ListBean omsProductBean = productResp.getData().getList().get(0);

                    ScmProduct scmProduct = new ScmProduct();
                    scmProduct.setTenantId(tenantId);
                    scmProduct.setProductCode(omsProductBean.getItemCode());
                    scmProduct.setProductName(omsProductBean.getItemName());
                    scmProduct.setProductUnit(omsProductBean.getUnitcode());
                    scmProduct.setRemark(omsProductBean.getFrgnName());
                    scmProduct.setCreateTime(System.currentTimeMillis());
                    scmProduct.setSource(source);
                    scmProduct.setBrand(omsProductBean.getBrand_name());

                    scmProductMapper.insertSelective(scmProduct);

                    ScmProductDetailOms scmProductDetailOms = new ScmProductDetailOms();
                    scmProductDetailOms.setTenantId(tenantId);
                    scmProductDetailOms.setScmProductId(scmProduct.getId());
                    scmProductDetailOms.setItemcode(omsProductBean.getItemCode());
                    scmProductDetailOms.setOmsProductId(String.valueOf(omsProductBean.getId()));
                    scmProductDetailOms.setItemname(omsProductBean.getItemName());
                    scmProductDetailOms.setFrgnname(omsProductBean.getFrgnName());
                    scmProductDetailOms.setBuyunitmsr(omsProductBean.getBuyUnitMsr());
                    scmProductDetailOms.setSalunitmsr(omsProductBean.getSalUnitMsr());
                    scmProductDetailOms.setUnitcode(omsProductBean.getUnitcode());
                    scmProductDetailOms.setKind1(omsProductBean.getU_Kind1());
                    scmProductDetailOms.setKind2(omsProductBean.getU_Kind2());
                    scmProductDetailOms.setKind3(omsProductBean.getU_Kind3());
                    scmProductDetailOms.setBrandname(omsProductBean.getBrand_name());
                    scmProductDetailOms.setModel(omsProductBean.getU_Model());
                    scmProductDetailOms.setParameter(omsProductBean.getU_Parameter());
                    scmProductDetailOms.setColor(omsProductBean.getU_Color());
                    scmProductDetailOms.setSuppcatnum(omsProductBean.getSuppCatNum());
                    scmProductDetailOms.setMtart(omsProductBean.getMtart());
                    scmProductDetailOms.setEcPreviewUrl(omsProductBean.getEcPreviewUrl());
                    scmProductDetailOms.setInvoiceName(omsProductBean.getInvoicename());
                    scmProductDetailOms.setTaxRateText(omsProductBean.getTax_rate_text());
                    scmProductDetailOms.setTaxCode(omsProductBean.getTax_code());
                    scmProductDetailOms.setCreateTime(System.currentTimeMillis());
                    scmProductDetailOms.setCreateUser(userId);
                    scmProductDetailOms.setUpdateTime(System.currentTimeMillis());
                    scmProductDetailOms.setUpdateUser(userId);

                    scmProductDetailOmsMapper.insertSelective(scmProductDetailOms);

                    productSyncStatus.setStatus(ProductSyncStatusEnum.Success);
                    productSyncStatus.setMsg("商品编号："+code+"同步成功");
                    productSyncStatus.setProductId(scmProduct.getId());
                }
            }
        } catch (Exception e) {
            log.error("syncProduct 出错了，source:{} ,code:{}",source,code, e);
            productSyncStatus.setStatus(ProductSyncStatusEnum.Fail);
            productSyncStatus.setMsg("商品编号："+code+"同步出错了，请联系管理员");

        }

        return productSyncStatus;
    }

    @Override
    public ScmProduct queryScmProductsByCode(Long tenantId, String code) {
        ScmProductExample example = new ScmProductExample();
        example.createCriteria().andTenantIdEqualTo(tenantId).andProductCodeEqualTo(code);
        List<ScmProduct>  list = scmProductMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }


    private OmsProductResp getOmsProductByCode( String productCode){

        log.info("getOmsProductByCode,productCode:{}",productCode);
        OmsProductResp resp = null;

        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");

            RequestBody body = RequestBody.create(mediaType, "{\"page\":1,\"pageSize\":100,\"search\":{\"code\":\""+productCode+"\",\"brandNameList\":[]},\"ofs_page_list\":1}");
            Request request = new Request.Builder()
                    .url("https://scs.officemate.cn/supplier/product/productSap/supplierProductSapList")
                    .method("POST", body)
                    .addHeader("authority", "scs.officemate.cn")
                    .addHeader("accept", "application/json, text/plain, */*")
                    .addHeader("accept-language", "zh-CN,zh;q=0.9")
                    .addHeader("appsecret", "hxBNGXUE22eXp4td01XSiUhUYPosQg7149646l3J6n5XHf8Qe6T2E868841HgB56")
                    .addHeader("authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvc2NzLm9mZmljZW1hdGUuY25cL29wZW5cL2F1dGhcL3N1cHBsaWVyTG9naW5CeUxpZm5yIiwiaWF0IjoxNzA2OTc0NTY3LCJleHAiOjE3MDc1NzkzNjcsIm5iZiI6MTcwNjk3NDU2NywianRpIjoiUE01OUpPR3dwU0VUTW5TRSIsInN1YiI6NDUyMjEsInBydiI6IjY2NDgyYjZkNjMzOTdiYjkyZjQ3NzQwNDMyN2RlNTE5ZGYzZmNlZmEiLCJwbGF0Zm9ybSI6Im9zcCJ9.7lzZ1NpQRqgH9JTLnlEjWh8IMQfx5jT4bp1kinBjdDA")
                    .addHeader("content-type", "application/json")
                    .addHeader("origin", "https://osp.officemate.cn")
                    .addHeader("referer", "https://osp.officemate.cn/")
                    .addHeader("sec-ch-ua", "\".Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"103\", \"Chromium\";v=\"103\"")
                    .addHeader("sec-ch-ua-mobile", "?0")
                    .addHeader("sec-ch-ua-platform", "\"macOS\"")
                    .addHeader("sec-fetch-dest", "empty")
                    .addHeader("sec-fetch-mode", "cors")
                    .addHeader("sec-fetch-site", "same-site")
                    .addHeader("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36")
                    .addHeader("usercode", "6C48A9-1374EF-EF2F6A-7DDBA1")
                    .addHeader("Cookie", "acw_tc=0a5cc90217070110357671892ea33ae13970b79811a99e0ac668f7da4b7fad; laravel_session=KMDRDgXc2fUgtxU8qQu1xyjFMSbJId5wHRcHXql9")
                    .build();
            Response response = client.newCall(request).execute();
            ResponseBody body2 = response.body();
            String productBody =  IOUtils.toString(body2.bytes(),"utf-8");
            String d = StringEscapeUtils.unescapeJava(productBody);

            resp = new Gson().fromJson(d,OmsProductResp.class);

        } catch (IOException e) {
            e.printStackTrace();
            log.error("getOmsProductByCode 出错了，",e);
        }
        return resp;

    }
}
